<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>调拨</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '95%'
        });
        
        //所有仓库
        var warehouseTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{number}|{name}', '</div></tpl>');
        var warehouseStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/warehouse/getAllWarehouse?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });

        var fromWarehouse = new Ext.form.ComboBox({
          store: warehouseStore,
          fieldLabel: '调出仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'from_warehouse_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: warehouseTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction:'all',
          selectOnFocus:true
        });

        var toWarehouse = new Ext.form.ComboBox({
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'to_warehouse_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: warehouseTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });

        //调拨日期
        var actionDate = new Ext.form.DateField({
          fieldLabel: '调拨日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "调拨日期必须选择",
          emptyText: '请选择日期...'
          //anchor: '50%'
        });
        
        var productTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">','<div style="float:left; width:220px">{name}</div><div style="float:left; width:90px">{number}</div>{is_suit}','</div></tpl>');
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product/getAllProducts?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            },{
              name: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //供应商产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          fieldLabel: '供应商产品',
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          pageSize: 25,
          //hideTrigger: false,
          tpl: productTemplate,
          displayField: 'name',
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var transferRecord = transferOrderDetailSM.getSelected();
          if (!transferRecord) {
            return false;
          }
          if (isDuplicateByProduct(transferOrderDetailDS,record.get('id'),transferRecord.id)){
            //删除当前记录
            transferOrderDetailDS.remove(transferRecord);
          }else{
            if (transferRecord.get('product_id') != record.get('id')){
              transferRecord.set('number',record.get('number'));
              transferRecord.set('spec',record.get('spec'));
              transferRecord.set('unit',record.get('unit'));
              transferRecord.set('quantity',1);
              transferRecord.set('stock_quantity',0);
              transferRecord.set('product_id',record.get('id'));
              transferRecord.set('is_suit',record.get('is_suit'));
            }
          }
        });


        //--------------------------------------------------------------------------
        //入库Grid Store
        var transferOrderDetailDS = new Ext.data.Store({
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }, {
              name: 'description'
            }, {
              name: 'quantity'
            },{
              name: 'product_id'
            }, {
              name: 'stock_quantity'
            }])
        });
        
        //生成产品Grid的CM
        var transferOrderDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var transferOrderDetailCM = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),transferOrderDetailSM,{
            id: 'common',
            header: 'DB',
            dataIndex: 'id',
            width: 50
          },{
            header: '产品名称',
            dataIndex: 'product_name',
            editor: productCBB,
            width: 370
          },{
            header: '产品ID',
            dataIndex: 'product_id',
            width: 50,
            hidden: false
          },{
            header: '产品编号',
            dataIndex: 'number',
            width: 90
          },{
            header: '规格',
            dataIndex: 'spec',
            width: 50
          },{
            header: '单位',
            dataIndex: 'unit',
            width: 50
          },{
            header: '数量',
            align: 'right',
            dataIndex: 'quantity',
            editor: new Ext.form.NumberField({
              allowBlank: false,
              allowDecimals: false,
              allowNegative: false
            }),
            width: 50
          },{
            header: '套装或单品',
            dataIndex: 'is_suit',
            width: 70
          },{
            header: '库存数量',
            align: 'right',
            dataIndex: 'stock_quantity',
            width: 60
          }
        ]);

        //生成要订单的产品的Grid
        var transferOrderDetailGrid = new Ext.grid.EditorGridPanel({
          store: transferOrderDetailDS,
          cm: transferOrderDetailCM,
          sm: transferOrderDetailSM,
          width: 900,
          height: 370,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = transferOrderDetailGrid.getStore().recordType;
                var productRecord = new Product({
                  product_name: '请选择产品'
                });
                transferOrderDetailGrid.stopEditing();
                transferOrderDetailDS.insert(0, productRecord);
                transferOrderDetailGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){                
                var record = transferOrderDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                transferOrderDetailDS.remove(record);
              }
            }]
        });

        //效验库存按钮
        var checkStockButton = new Ext.Button({
          text: '检查库存',
          tooltip: '检查库存',
          iconCls: 'icon-save',
          handler: function(){
            if(transferFormPanel.form.isValid()){
              //同仓库不能调拨
              if(fromWarehouse.getValue() == toWarehouse.getValue() ){
                Ext.MessageBox.alert('提示', "同仓不能调拨！");
              }else{
                //没有添加产品，则提示
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }

                var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }
                var allJsonStr = transferFormPanel.getForm().getValues();
                allJsonStr = Ext.util.JSON.encode(allJsonStr);
                allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                //alert(allJsonStr);
                Ext.Ajax.request({
                  url : '/transfer_order/check_stock',
                  success : function (result, request) {
                    //alert(Ext.util.JSON.decode(result.responseText).length);
                    var jsonArray = Ext.util.JSON.decode(result.responseText);
                    var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
                    for (var i = 0 ; i< jsonArray.length;i++){                      
                      for(var j = 0; j< records.length ;j++){
                        var record = records[j];
                        if(record.get('product_id') == jsonArray[i].product_id){
                          record.set('stock_quantity',jsonArray[i].quantity);
                          break;
                        }
                      }
                    }
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  },
                  method : 'POST',
                  params : {
                    data : Ext.util.JSON.encode(allJsonStr),
                    authenticity_token: authToken.getValue()
                  }
                });
              }
            }
          }
        });

        //提交按钮
        var transferButton = new Ext.Button({
          text: '提交',
          tooltip: '提交',
          iconCls: 'icon-save',
          handler: function(){
            if(transferFormPanel.form.isValid()){
              //同仓库不能调拨
              if(fromWarehouse.getValue() == toWarehouse.getValue() ){
                Ext.MessageBox.alert('提示', "同仓不能调拨！");
              }else{
                //没有添加产品，则提示
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }
                
                var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
                if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您还没有选择有效的产品或选择的产品数量为0！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                }

                //再取得一次库存
                checkStockButton.handler();
                //检查一下，如果要调拨的货比仓库的库存还要，就提示
                var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
                for (var i = 0 ; i< records.length;i++){
                  var record = records[i]
                  if (record.get('quantity')  > record.get('stock_quantity') ){
                    Ext.MessageBox.show({
                      title: '提示',
                      msg: "您要调拨的货品数量有大于当前仓存数量的，请检查后提交！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                    return;
                    break;
                  }
                }
                    
                this.disable();
                var allJsonStr = transferFormPanel.getForm().getValues();
                allJsonStr = Ext.util.JSON.encode(allJsonStr);
                allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
                allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
                //alert(allJsonStr);
                Ext.Ajax.request({
                  url : '/transfer_order/create',
                  success : function (result, request) {
                    newTransferWin.destroy();
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                    newTransferWin.destroy();
                  },
                  method : 'POST',
                  params : {
                    data : Ext.util.JSON.encode(allJsonStr),
                    authenticity_token: authToken.getValue()
                  }
                });
              }
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = new Ext.Button({
          text: '暂存',
          tooltip: '暂时保存销售订单。',
          iconCls: 'temp-save',
          handler: function(){
            //同仓库不能调拨
            if(fromWarehouse.getValue() == toWarehouse.getValue() ){
              Ext.MessageBox.alert('提示', "同仓不能调拨！");
              return;
            }
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (transferFormPanel.form.isValid()){

              var productsJsonStr = gridStoreToJson(transferOrderDetailDS,rejectKeyArray);
              if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (transferOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //再取得一次库存
              checkStockButton.handler();
              //检查一下，如果要调拨的货比仓库的库存还要，就提示
              var records = transferOrderDetailDS.getRange(0,transferOrderDetailDS.getCount());
              for (var i = 0 ; i< records.length;i++){
                var record = records[i]
                if (record.get('quantity')  > record.get('stock_quantity') ){
                  Ext.MessageBox.show({
                    title: '提示',
                    msg: "您要调拨的货品数量有大于当前仓存数量的，请检查后提交！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                  return;
                  break;
                }
              }

                
              this.disable();
              var allJsonStr = transferFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/transfer_order/create',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  newTransferWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  newTransferWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //关闭
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newTransferWin.destroy();
          }
        });
        
        var transferFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'transfer_form',
          labelWidth: 55,
          width: '900',
          labelAlign: 'right',
          frame : true,
          url: '/transferOrder/create',
          method: 'GET',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .35,
                  layout: 'form',
                  border: false,
                  items: [fromWarehouse]
                }, {
                  columnWidth: .35,
                  layout: 'form',
                  border: false,
                  items: [toWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [transferOrderDetailGrid]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },temporary],
          buttons: [checkStockButton,transferButton,tempSaveButton,closeButton]
        });
        transferFormPanel.render('new_transfer_form');

        function checkStockQuantity(){
          
        }
      })
    </script>
  </head>
  <body>
    <div id="new_transfer_form"></div>
  </body>
</html>
